/*
 * LoginRestController.java
 * Copyright (c) 2014, 2019, Kiri. 
 * All rights reserved.
 */
package com.onesalt.web.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.onesalt.common.ExceptionConstants;
import com.onesalt.domain.Kitchen;
import com.onesalt.domain.User;
import com.onesalt.domain.UserLogin;
import com.onesalt.service.SystemService;
import com.onesalt.web.api.request.MobileLoginRequest;
import com.onesalt.web.api.response.LoginResponse;

/**
 * @author kiri
 * @date 2015年4月12日
 * @version 1.0
 */
@RestController
@RequestMapping("/api")
public class LoginRestController extends AbstractRestController {
	
	@Autowired
	private SystemService systemService;
	
	@RequestMapping(value = "/loginByMobile", method = RequestMethod.POST)
	public LoginResponse loginByMobile(@ModelAttribute MobileLoginRequest request) {
		User user = null;
		if (StringUtils.hasText(request.getToken())) {
			// ReLogin
			user = getValidUser(request);
		} else {
			user = getUserService().findOrCreateUserByMobile(request.getMobile());
			if (user == null) {
				throw ExceptionConstants.USER_NOT_EXISTS_EXCEPTION;
			}
		}
		
		UserLogin login = getLoginService().login(user.getUserId(), UserLogin.LoginType.MOBILE, request.getClient(), request.getVersion(),
				request.getDeviceId(), request.getLastAppOpenTime());
		if (login == null) {
			throw ExceptionConstants.LOGIN_FAILED_EXCEPTION;
		}
		user.setLogin(login);
		return createResponseByUser(user);
	}
	
	private LoginResponse createResponseByUser(User user) {
		Kitchen kitchen = getUserService().getKitchenRepository().findTopByCookId(user.getUserId());
		user.setKitchen(kitchen);
		LoginResponse resp = new LoginResponse();
		resp.setUser(user);
		resp.setSystemParams(systemService.getAllClientParams());
		return resp;
	}
}
